package map.web;

import map.core.*;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.List;

public class TestServlet extends HttpServlet {

    static   MapRenderer renderer;


    synchronized static MapRenderer getMapRenderer(){
        if(renderer == null){
            File file = new File("E:\\data\\2.nc");
            NetCDFSource netCDFSource = new NetCDFSource(file);
            List<NetCDFLayerBaseInfo> layers = netCDFSource.listLayerBaseInfo();
              renderer = MapRenderer.create(netCDFSource.getLayer(layers.get(0).getName()));
        }
        return renderer;
    }


    private RasterLayerStyle createStyle(){


        RasterLayerStyle style = new RasterLayerStyle(0);
        style.addStop(0.001,0X4fdc14);
        style.addStop(0.002,0Xbbf22f);
        style.addStop(0.003,0Xfcf03f);
        style.addStop(0.004,0Xfbc83e);
        style.addStop(0.005,0Xf9963c);
        style.addStop(0.006,0Xf5623b);
        style.addStop(0.007,0Xf22751);
        style.addStop(0.009,0Xf34085);


        return style;
    }


    @Override
   synchronized protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        byte[] content = null;
        String action = req.getParameter("action");
        switch (action) {
            case "getImage": {

                content = getMapRenderer().getImage(0,createStyle(), 1.0);

                break;
            }
            case "getImageWithBounds": {
                double minLon = Double.parseDouble(req.getParameter("minLon"));
                double maxLon = Double.parseDouble(req.getParameter("maxLon"));
                double minLat = Double.parseDouble(req.getParameter("minLat"));
                double maxLat = Double.parseDouble(req.getParameter("maxLat"));


                LonLatBounds bounds = new LonLatBounds(minLon, maxLon, minLat, maxLat);
                content = getMapRenderer().getImage(0,createStyle(), 1.0, bounds);

            }
        }
        if(content !=null){
            resp.setContentType("image/png");
            resp.getOutputStream().write(content);
            resp.flushBuffer();

        }



    }
}
